package org.wicket.jbpm.page.admin;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.jbpm.graph.def.ProcessDefinition;
import org.wicket.jbpm.WicketJBPMSession;
import org.wicket.jbpm.engine.exception.WicketJbpmException;
import org.wicket.jbpm.engine.spring.JbpmCoreEngine;
import org.wicket.jbpm.engine.spring.JbpmProcessEngine;
import org.wicket.jbpm.engine.workflow.WfPath;
import org.wicket.jbpm.page.WicketJBPMBasePage;
import org.wicket.jbpm.task.panel.UploadProcessPanel;

/**
 * 
 * @author Emmanuel Nollase - emanux
 * created 2009 10 7 - 18:01:12
 */
public class JbpmProcessDefPage extends WicketJBPMBasePage
{

    @SpringBean private JbpmProcessEngine jbpmProcessEngine;
    @SpringBean private JbpmCoreEngine jbpmCoreEngine;
    
    public JbpmProcessDefPage()
    {
	final String user = WicketJBPMSession.get().getUser().getCd();
	
	final FeedbackPanel feedback = new FeedbackPanel("feedback");
	add(feedback.setOutputMarkupId(true));
	
	final UploadProcessPanel upload = new UploadProcessPanel("upload");
	add(upload);
	
	List<ProcessDefinition> defs = jbpmProcessEngine.getDefinitions();
	
	final ListView lstDefs = new ListView("processDefs", defs)
	{
	    
	    @Override
	    protected void populateItem(ListItem item)
	    {
		final ProcessDefinition def = (ProcessDefinition) item.getModelObject();
		item.setModel(new CompoundPropertyModel(def));
		item.add(new Label("name"));
		item.add(new Label("version"));
		item.add(new Label("description"));
		item.add(new AjaxFallbackLink("start",item.getModel())
		{
		    @Override
		    public void onClick(AjaxRequestTarget target)
		    {
			final String procName = ( (ProcessDefinition) getModelObject()).getName();
			final ProcessDefinition def = jbpmProcessEngine.getDefinition(procName);
			final WfPath wpath = jbpmCoreEngine.startProcessInstance(def, user, null);
			
			try
			{
			    jbpmCoreEngine.signalTask(wpath.id);
			    feedback.info("Successfully start process: "+procName);
			} catch (WicketJbpmException e)
			{
			    e.printStackTrace();
			    feedback.error("Error occured: "+e.getMessage());
			}
			target.addComponent(feedback);
		    }
		});
	    }
	};
	add(lstDefs);
    }
}

